package org.example.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.example.entity.Menu;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.exception.LoginException;
import org.example.mapper.MenuMapper;
import org.example.mapper.RoleMapper;
import org.example.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 查询用户权限
 */
@Service("UserDetailsServiceImpl")
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userService;
    private final RoleMapper iRoleService;
    private final MenuMapper iMenuService;

    // 登录调用的方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userService.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,username)); // 按名字查询，用户名等于登录名
        if (user==null)throw new UsernameNotFoundException("用户不存在");
        // 获取用户所有的角色列表
        List<Role> roleList=iRoleService.selectbyUserId(user.getUserId()); // 根据用户id找到所有的角色
        // 循环角色，把角色id一个个 取出来，放到数组里面
        Long[] roleIds= roleList.stream().mapToLong(Role::getRoleId).boxed().toArray(Long[]::new);
        // 根据角色获取所有菜单
        List<Menu> menuList=iMenuService.selectByRoleIds(roleIds);
        // 存储到redis
//        String uuid= UUID.randomUUID().toString();
        Set<String> roleNames=roleList.stream().map(Role::getRoleKey).collect(Collectors.toSet());
        Set<String> perms=menuList.stream().filter(menu -> StringUtils.hasText(menu.getPerms())).map(Menu::getPerms).collect(Collectors.toSet());
        UserDetailsImpl userDetails=new UserDetailsImpl();
        userDetails.setRoleKeySet(roleNames);
        userDetails.setPermsSet(perms);
        userDetails.setUsername(user.getUserName());
        userDetails.setPassword(user.getPassword());
        userDetails.setStatus(user.getStatus());
        userDetails.setUser(user);
        return userDetails;
    }
}
